package com.av.bcacc.myapidemo.provider;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import com.av.bcacc.myapidemo.R;
import com.av.bcacc.myapidemo.databinding.ActivityProviderBinding;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ProviderActivity extends AppCompatActivity {
    public static final String TAG = ProviderActivity.class.getSimpleName();
    private ActivityProviderBinding providerBinding;
    private List<User> userList = new ArrayList<>();
    private Uri userUri = Uri.parse("content://hwl.myprovider/user");
    private ContentResolver resolver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        providerBinding = DataBindingUtil.setContentView(this, R.layout.activity_provider);
        resolver = getContentResolver();
        resolver.delete(userUri,null,null);
        for (int i = 0; i < 10; i++) {
            ContentValues values = new ContentValues();
            values.put("name", "test" + i);
            values.put("age", new Random().nextInt());
            values.put("address", "左岭新城" + i + "社区");
            resolver.insert(userUri, values);
        }
        // 通过ContentResolver 向ContentProvider中查询数据
        Cursor cursor = resolver.query(userUri, new String[]{"name", "age", "address"}, null, null, null);
        while (cursor.moveToNext()) {

            // 将表中数据全部输出
            String name = cursor.getString(0);
            int age = cursor.getInt(1);
            String address = cursor.getString(2);
            Log.d(TAG,"name:"+name+" age:"+age + " address:"+address);
            User user=new User();
            user.name=name;
            user.age=age;
            user.address=address;
            userList.add(user);
        }
        cursor.close();

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        providerBinding.recyclerView.setLayoutManager(layoutManager);
        providerBinding.recyclerView.setHasFixedSize(true);
        ProviderAdapter providerAdapter = new ProviderAdapter(userList);
        providerBinding.recyclerView.setAdapter(providerAdapter);

    }
}
